# -*- coding: utf-8 -*-
# @Time : 2022/2/27 9:04
# @Author : Liuqing
# @File : spider.py
# @Software : PyCharm

import urllib.request
import urllib.error
import re
import xlwt
import sqlite3

from bs4 import BeautifulSoup


def main():
    baseurl = "https://movie.douban.com/top250?start="
    # 1.爬取网页
    data_list = get_data(baseurl)
    # 3.存储数据
    save_path = "豆瓣电影TOP250.xls"
    sava_data(data_list, save_path)


# 创建正则表达式对象，或者规则
find_link = re.compile(r'<a href="(.*?)">')  # 影片链接
find_img_src = re.compile(r'<img.*src="(.*?)"', re.S)  # 影片封面re.S 让换行符包含在字符中
find_title = re.compile(r'<span class="title">(.*)</span>')  # 影片标题
find_rating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')  # 影片评分
find_judge = re.compile(r'<span>(\d*)人评价</span>')  # 评价人数
find_inquest = re.compile(r'<span class="inq">(.*)</span>')  # 影片概况
find_bd = re.compile(r'<p class="">(.*?)</p>', re.S)  # 影片相关信息


# 发起请求
def ask_url(url):
    header = {
        "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 "
            "Safari/537.36 "
    }

    request = urllib.request.Request(url, headers=header)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html


# 爬取网页 & 数据解析
def get_data(baseurl):
    data_list = []
    for i in range(0, 10):
        url = baseurl + str(i * 25)
        html = ask_url(url)

        # 解析数据
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all("div", class_="item"):
            # print(item)
            data = []
            item = str(item)

            # 通过正则匹配提取影片链接并加入到data列表中
            link = re.findall(find_link, item)[0]
            data.append(link)

            img_src = re.findall(find_img_src, item)[0]
            data.append(img_src)

            titles = re.findall(find_title, item)
            # 如果影片名有多个
            if len(titles) == 2:
                # 取中文影片名
                cn_title = titles[0]
                data.append(cn_title)
                # 取英文影片名并格式化
                foreign_title = titles[1].replace("/", "")
                data.append(foreign_title)
            else:
                data.append(titles[0])
                data.append(" ")

            rating = re.findall(find_rating, item)[0]
            data.append(rating)

            judge = re.findall(find_judge, item)[0]
            data.append(judge)

            inq = re.findall(find_inquest, item)
            if len(inq) != 0:
                inq = inq[0].replace("。", "")
                data.append(inq)
            else:
                data.append(" ")

            bd = re.findall(find_bd, item)[0]
            bd = re.sub(r'<br(\s+)?/>(\s+)?', " ", bd)    # 去掉<br/>
            bd = re.sub("/", " ", bd)     # 替换
            data.append(bd.strip())       # 去除两端空格再存储

            # 最后把data存入datalist中
            data_list.append(data)

    return data_list


# 保存到Excel
def sava_data(data_list, save_path):
    book = xlwt.Workbook(encoding="utf-8", style_compression=0)
    sheet = book.add_sheet("豆瓣电影TOP250", cell_overwrite_ok=True)
    col = ("电影链接", "图片链接", "影片中文名", "影片外文名", "评分", "评价人数", "概况", "相关信息")
    for i in range(0, 8):
        sheet.write(0, i, col[i])      # 添加列名
    for i in range(0, 250):
        data = data_list[i]
        for j in range(0, 8):
            sheet.write(i+1, j, data[j])

    book.save(save_path)


if __name__ == "__main__":
    main()
    print("爬取完毕~ ")
